PHP Core / OOPs / Data sharing between instances of different class
Data sharing between object of different classes
-
Note
Using Dependency Injection:
Pass an instance of one class as a parameter to the constructor or a method of another class.
class ClassA { private $sharedData; public function setData($data) { $this->sharedData = $data; } public function getData() { return $this->sharedData; } } class ClassB { private $classA; public function __construct(ClassA $classA) { $this->classA = $classA; } public function processData() { $data = $this->classA->getData(); // Process data here } } // Example usage $classA = new ClassA(); $classB = new ClassB($classA); $classA->setData("Hello, World!"); $classB->processData(); Using a Singleton Pattern:
Implement a singleton pattern to create a single instance of a class that manages shared data. Other classes can then access this instance.
class SharedDataSingleton { private static $instance; private $sharedData; private function __construct() {} public static function getInstance() { if (!self::$instance) { self::$instance = new SharedDataSingleton(); } return self::$instance; } public function setData($data) { $this->sharedData = $data; } public function getData() { return $this->sharedData; } } class ClassA { public function setData($data) { SharedDataSingleton::getInstance()->setData($data); } public function getData() { return SharedDataSingleton::getInstance()->getData(); } } class ClassB { public function processData() { $data = SharedDataSingleton::getInstance()->getData(); // Process data here } } // Example usage $classA = new ClassA(); $classB = new ClassB(); $classA->setData("Hello, World!"); $classB->processData();